package com.focusai.efairy.ui.activity.project;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.focusai.efairy.R;
import com.focusai.efairy.model.request.AddUserAndDevToProjectRequest;
import com.focusai.efairy.model.response.ProjectManageResponse;
import com.focusai.efairy.network.HttpManager;
import com.focusai.efairy.network.Response;
import com.focusai.efairy.network.exception.NetworkException;
import com.focusai.efairy.ui.adapter.project.ProjectUserDevAdapter;
import com.focusai.efairy.ui.base.SwipeBackBaseActivity;
import com.focusai.efairy.utils.PhoneCheckUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by luo_guangwen on 2017/9/12.
 */

public class ProjectAddUserActivity extends SwipeBackBaseActivity implements View.OnClickListener {
    public static final String KEY_PROJECT_ID = "key_project_id";
    private static final int REQUEST_CODE_DEV = 0X15;

    private RecyclerView mRecyclerView;
    private EditText text_user_name;
    private EditText text_user_phone;
    private TextView text_dev_num;
    private ProjectUserDevAdapter mAdapter;
    private ArrayList<ProjectManageResponse.DevItem> mList;
    private String projectId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_project_edit_user);
        initView();
        setDefaultValues();
        loadData();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuItem menuItem1 = menu.add(MENU_GROUP_ID, MENU_ITEM_ADD, 0, R.string.save).setTitle(R.string.save);
        MenuItemCompat.setShowAsAction(menuItem1, MenuItemCompat.SHOW_AS_ACTION_ALWAYS);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == MENU_ITEM_ADD) {
            saveUser();
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void initView() {
        mRecyclerView = findView(R.id.rcyc_view);
        text_user_name = findView(R.id.text_user_name);
        text_user_phone = findView(R.id.text_user_phone);
        text_dev_num = findView(R.id.text_dev_num);
        findView(R.id.llayout_dev_manage).setOnClickListener(this);

    }

    @Override
    protected void setDefaultValues() {
        if (getIntent() != null) {
            projectId = getIntent().getStringExtra(KEY_PROJECT_ID);
        }
        setCenterTitleName("新增用户");
        mList = new ArrayList<>();
        mAdapter = new ProjectUserDevAdapter();
        mAdapter.refreshData(mList);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mRecyclerView.setAdapter(mAdapter);
    }

    private void saveUser() {
        if (TextUtils.isEmpty(text_user_name.getText().toString())) {
            showToast("请输入用户名称");
            return;
        }
        String phone = text_user_phone.getText().toString();
        if (TextUtils.isEmpty(phone)) {
            showToast("请输入用户手机号");
            return;
        }
        if (!PhoneCheckUtils.isChinaPhoneLegal(phone)) {
            showToast("请输入正确手机号");
            return;
        }
        showSingleDialog("正在提交数据..");
        List<Long> ids = new ArrayList<>();
        for (ProjectManageResponse.DevItem devItem : mList) {
            ids.add(devItem.efairydevice_id);
        }
        HttpManager.getInstance().sendRequest(new AddUserAndDevToProjectRequest(projectId, phone,
                text_user_name.getText().toString(),ids, new Response.Listener<String>() {
            @Override
            protected void onSuccess(String response) {
                closeSingleDialog();
                showToast("保存数据成功");
                setResult(RESULT_OK);
                finish();
            }

            @Override
            protected void onFail(NetworkException exception) {
                closeSingleDialog();
                doException(exception);
            }
        }));
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.llayout_dev_manage:
                Intent intent = new Intent(getContext(), ProjectSelectDevListActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable(ProjectSelectDevListActivity.KEY_SELETED_ITEMS, mList);
                bundle.putString(ProjectSelectDevListActivity.KEY_PROJECT_ID, projectId);
                intent.putExtras(bundle);
                startActivityForResult(intent, REQUEST_CODE_DEV);
                break;
            default:
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_CODE_DEV) {
                if (data != null && data.getExtras() != null) {
                    ArrayList<ProjectManageResponse.DevItem> list = (ArrayList<ProjectManageResponse.DevItem>) data.getExtras()
                            .getSerializable(ProjectSelectDevListActivity.KEY_SELETED_ITEMS);
                    mList.clear();
                    mList.addAll(list);
                    mAdapter.notifyDataSetChanged();
                    text_dev_num.setText(getResources().getString(R.string.manager_device, mList.size()));
                }
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}
